package com.pbd.server;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.pbd.client.MemberService;
import com.pbd.shared.ALBUMMASTER;
import com.pbd.shared.BUSINESSCATEGORYRELATION;
import com.pbd.shared.CORRESPONDENCEDETAIL;
import com.pbd.shared.MEDIARELATION;
import com.pbd.shared.PARTY;
import com.pbd.shared.PARTYCONTACT;

public class MemberServiceImpl extends RemoteServiceServlet implements MemberService {

	@Override
	public String saveOrUpdateMember(PARTY party, Map partyRelatedInfoMap) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Set partyContactSet = (Set) partyRelatedInfoMap.get("partyContact");
		Set businessCategorySet = (Set) partyRelatedInfoMap.get("businessCategory");
		Set correspondenceSet = (Set) partyRelatedInfoMap.get("correspondenceDetails");
		Set<ALBUMMASTER> logoAlbumSet = (Set) partyRelatedInfoMap.get("logoAlbum");
		if (partyContactSet != null)
			party.setPartyContacts(partyContactSet);
		if (businessCategorySet != null)
			party.setBusinessCategoryRelation(businessCategorySet);
		if (correspondenceSet != null)
			party.setCorrespondence(correspondenceSet);

		PARTY savedParty = (PARTY) hibernateServiceImpl.saveObject(party);
		if (logoAlbumSet != null) {
			Iterator<ALBUMMASTER> albumIt = logoAlbumSet.iterator();
			ALBUMMASTER albumMaster = null;
			while (albumIt.hasNext()) {
				albumMaster = albumIt.next();
				albumMaster.setParty(savedParty);
				albumMaster.setAlbumCode("Logo Code " + savedParty.getPartyId());
			}
			hibernateServiceImpl.saveObject(albumMaster);
		}
		return "Success";
	}

	public Map getParty(Long partyId) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Map partyMap = new HashMap();
		List dataList = hibernateServiceImpl.getSearchResult(" select partyId,name,type,webSite,contactPerson,keywords,joinedDate,isActive from PARTY where partyId=" + partyId);
		partyMap.put("PARTYINFO", dataList);
		List partyContactList = hibernateServiceImpl.getSearchResult("select partyContactId,address,area,cityname,statename,countryname,pincode,type from PARTYCONTACT where partyId=" + partyId);
		partyMap.put("PARTYCONTACT", partyContactList);
		List businessCategoryRelationList = hibernateServiceImpl.getSearchResult("select bcr.id as businesscategoryRelationID ,bc.id as businesscategoryid , bc.name as businesscategoryname ,bcr.isprimary as isprimary from BUSINESSCATEGORYRELATION bcr inner join BUSINESSCATEGORY bc on bc.id = bcr.businessCategoryId where bcr.partyId=" + partyId);
		partyMap.put("BUSINESSCATEGORY", businessCategoryRelationList);
		List correspondenceDetailList = hibernateServiceImpl.getSearchResult("select correspondenceDetailId,value,type from CORRESPONDENCEDETAIL where partyId=" + partyId);
		partyMap.put("CORRESPONDENCEDETAILS", correspondenceDetailList);

		List logoAlbumList = hibernateServiceImpl.getSearchResult("select mr.mediaSource,mr.id,a.albumid from MEDIARELATION mr inner join ALBUMMASTER a on a.albumid = mr.albumid where a.partyid=" + partyId + " AND mr.mediaType='Logo/Image'");
		partyMap.put("LOGOALBUM", logoAlbumList);
		return partyMap;
	}

	public static void main(String[] args) {
		MemberServiceImpl ms = new MemberServiceImpl();
		ms.getParty(1L);
	}

	@Override
	public List<Map> getPartyList(String whereClause, String[] filterAndOrderExtraColumnExps) {
		List<Map> partyList = new ArrayList<Map>();

		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		List dataList = hibernateServiceImpl.findObjectsOnObjectBasis("PARTY", new String[] { "correspondence", "businessCategoryRelation", "partyContacts", "albumRelation", "albumRelation.albumMediaRelation" }, whereClause, filterAndOrderExtraColumnExps);
		int dataListSize = dataList == null ? 0 : dataList.size();
		for (int index = 0; index < dataListSize; index++) {
			PARTY party = (PARTY) dataList.get(index);
			Set<PARTYCONTACT> partyContactSet = party.getPartyContacts();
			List<PARTYCONTACT> partyContactList = new ArrayList<PARTYCONTACT>(partyContactSet);
			PARTYCONTACT partyContact = partyContactList.get(0);
			Map memberMap = new HashMap();
			StringBuffer sbAddress = new StringBuffer();
			if (partyContact.getAddress().charAt(partyContact.getAddress().length() - 1) == ',')
				sbAddress.append(partyContact.getAddress());
			else
				sbAddress.append(partyContact.getAddress()).append(", ");
			sbAddress.append(partyContact.getArea()).append(", ");
			sbAddress.append(partyContact.getCityName()).append(" ");

			if (partyContact.getPinCode() != null)
				sbAddress.append(" - ").append(partyContact.getPinCode());
			memberMap.put("Name", party.getName());
			memberMap.put("Id", party.getPartyId().toString());
			memberMap.put("Address", sbAddress.toString());
			Set<CORRESPONDENCEDETAIL> correspondenceSet = party.getCorrespondence();
			List<CORRESPONDENCEDETAIL> correspondenceDetailList = new ArrayList<CORRESPONDENCEDETAIL>(correspondenceSet);
			String phoneNo = getPhoneNo(correspondenceDetailList);
			if (phoneNo.trim().length() > 0)
				memberMap.put("Phone", phoneNo);
			String faxNo = getFaxNo(correspondenceDetailList);
			if (faxNo.trim().length() > 0)
				memberMap.put("Fax", faxNo);
			String mobileNo = getMobileNo(correspondenceDetailList);
			if (mobileNo.trim().length() > 0)
				memberMap.put("Mobile", mobileNo);
			String email = getEmail(correspondenceDetailList);
			if (email.trim().length() > 0)
				memberMap.put("Email", email);
			String teleFax = getTeleFaxNo(correspondenceDetailList);
			if (teleFax.trim().length() > 0)
				memberMap.put("TeleFax", teleFax);
			memberMap.put("Area", partyContact.getArea());

			Set<ALBUMMASTER> albumSet = party.getAlbumRelation();
			List albumList = new ArrayList<ALBUMMASTER>(albumSet);
			int albumSize = albumList == null ? 0 : albumList.size();

			for (int albumIndex = 0; albumIndex < albumSize; albumIndex++) {
				ALBUMMASTER albumMaster = (ALBUMMASTER) albumList.get(albumIndex);
				if (albumMaster.getAlbumCode().contains("Logo")) {
					Set<MEDIARELATION> albumMediaRelationSet = albumMaster.getAlbumMediaRelation();
					memberMap.put("LogoPath", ((new ArrayList<MEDIARELATION>(albumMediaRelationSet)).get(0)).getMediaSource());
				}
			}
			if (party.getCreatedDate() != null) {
				DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
				memberMap.put("PostedOn", df.format(party.getCreatedDate()));
			}
			partyList.add(memberMap);

		}
		return partyList;
	}

	@Override
	public Map getPartyInfoMap(Long partyId) {
		Map memberMap = new HashMap();
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		List dataList = hibernateServiceImpl.findObjectsOnObjectBasis("PARTY", new String[] { "correspondence", "businessCategoryRelation", "partyContacts", "albumRelation", "albumRelation.albumMediaRelation" }, "PARTY.partyId=" + partyId, null);
		int dataListSize = dataList == null ? 0 : dataList.size();
		for (int index = 0; index < dataListSize; index++) {
			PARTY party = (PARTY) dataList.get(index);
			Set<PARTYCONTACT> partyContactSet = party.getPartyContacts();
			List<PARTYCONTACT> partyContactList = new ArrayList<PARTYCONTACT>(partyContactSet);
			PARTYCONTACT partyContact = partyContactList.get(0);
			StringBuffer sbAddress = new StringBuffer();
			if (partyContact.getAddress().charAt(partyContact.getAddress().length() - 1) == ',')
				sbAddress.append(partyContact.getAddress());
			else
				sbAddress.append(partyContact.getAddress()).append(", ");
			sbAddress.append("<br>").append(partyContact.getArea()).append(", ");
			sbAddress.append(partyContact.getCityName()).append(" ");

			memberMap.put("Name", party.getName());
			if (party.getContactPerson().trim().length() > 0)
				memberMap.put("Contact Person", party.getContactPerson());
			memberMap.put("Id", party.getPartyId().toString());
			memberMap.put("Address", sbAddress.toString());
			if (partyContact.getPinCode() != null)
				memberMap.put("PinCode", partyContact.getPinCode());

			Set<CORRESPONDENCEDETAIL> correspondenceSet = party.getCorrespondence();
			List<CORRESPONDENCEDETAIL> correspondenceDetailList = new ArrayList<CORRESPONDENCEDETAIL>(correspondenceSet);
			String phoneNo = getPhoneNo(correspondenceDetailList);
			if (phoneNo.trim().length() > 0)
				memberMap.put("Phone", phoneNo);
			String faxNo = getFaxNo(correspondenceDetailList);
			if (faxNo.trim().length() > 0)
				memberMap.put("Fax", faxNo);
			String mobileNo = getMobileNo(correspondenceDetailList);
			if (mobileNo.trim().length() > 0)
				memberMap.put("Mobile", mobileNo);
			String email = getEmail(correspondenceDetailList);
			if (email.trim().length() > 0)
				memberMap.put("Email", email);
			String teleFax = getTeleFaxNo(correspondenceDetailList);
			if (teleFax.trim().length() > 0)
				memberMap.put("TeleFax", teleFax);

			if (party.getWebSite() != null)
				memberMap.put("WebSite", party.getWebSite());
			memberMap.put("Area", partyContact.getArea());

			Set<ALBUMMASTER> albumSet = party.getAlbumRelation();
			List albumList = new ArrayList<ALBUMMASTER>(albumSet);
			int albumSize = albumList == null ? 0 : albumList.size();
			List albumDataList = new ArrayList();
			for (int albumIndex = 0; albumIndex < albumSize; albumIndex++) {
				ALBUMMASTER albumMaster = (ALBUMMASTER) albumList.get(albumIndex);
				if (albumMaster.getAlbumCode().contains("Logo")) {
					Set<MEDIARELATION> albumMediaRelationSet = albumMaster.getAlbumMediaRelation();
					memberMap.put("LogoPath", ((new ArrayList<MEDIARELATION>(albumMediaRelationSet)).get(0)).getMediaSource());
				} else {
					Set<MEDIARELATION> albumMediaRelationSet = albumMaster.getAlbumMediaRelation();
					Iterator<MEDIARELATION> mediaRelIt = albumMediaRelationSet.iterator();
					while (mediaRelIt.hasNext()) {
						MEDIARELATION mediaRelation = mediaRelIt.next();
						if (mediaRelation.getIsDefault()) {
							ArrayList dataValueList = new ArrayList();
							dataValueList.add(albumMaster.getAlbumId());
							dataValueList.add(albumMaster.getAlbumTitle());
							dataValueList.add(albumMaster.getLayout());
							if (albumMaster.getLayout().equalsIgnoreCase("Description")) {
								dataValueList.add("/images/company_profile.jpg");
							} else
								dataValueList.add(mediaRelation.getMediaSource());
							albumDataList.add(dataValueList);
						}
					}
				}
			}

			if (party.getCreatedDate() != null) {
				DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
				memberMap.put("PostedOn", df.format(party.getCreatedDate()));
			}

			if (albumDataList.size() > 0)
				memberMap.put("AlbumList", albumDataList);

		}
		return memberMap;
	}

	private String getMobileNo(List<CORRESPONDENCEDETAIL> correspondenceDetailList) {
		StringBuffer sbMobileNo = new StringBuffer();
		Iterator<CORRESPONDENCEDETAIL> itMobile = correspondenceDetailList.iterator();
		while (itMobile.hasNext()) {
			CORRESPONDENCEDETAIL corresDetail = itMobile.next();
			if (corresDetail.getType().equalsIgnoreCase("Mobile"))
				sbMobileNo.append(corresDetail.getValue()).append(" / ");
		}

		if (sbMobileNo.length() > 3)
			return sbMobileNo.substring(0, sbMobileNo.length() - 3);
		return "";
	}

	private String getPhoneNo(List<CORRESPONDENCEDETAIL> correspondenceDetailList) {
		StringBuffer sbPhoneNo = new StringBuffer();
		Iterator<CORRESPONDENCEDETAIL> itPhone = correspondenceDetailList.iterator();
		while (itPhone.hasNext()) {
			CORRESPONDENCEDETAIL corresDetail = itPhone.next();
			if (corresDetail.getType().equalsIgnoreCase("Phone"))
				sbPhoneNo.append(corresDetail.getValue()).append(" / ");
		}

		if (sbPhoneNo.length() > 3)
			return sbPhoneNo.substring(0, sbPhoneNo.length() - 3);
		return "";
	}

	private String getFaxNo(List<CORRESPONDENCEDETAIL> correspondenceDetailList) {
		StringBuffer sbFaxNo = new StringBuffer();
		Iterator<CORRESPONDENCEDETAIL> itFax = correspondenceDetailList.iterator();
		while (itFax.hasNext()) {
			CORRESPONDENCEDETAIL corresDetail = itFax.next();
			if (corresDetail.getType().equalsIgnoreCase("Fax"))
				sbFaxNo.append(corresDetail.getValue()).append(" / ");
		}

		if (sbFaxNo.length() > 3)
			return sbFaxNo.substring(0, sbFaxNo.length() - 3);
		return "";
	}

	private String getTeleFaxNo(List<CORRESPONDENCEDETAIL> correspondenceDetailList) {
		StringBuffer sbTeleFaxNo = new StringBuffer();
		Iterator<CORRESPONDENCEDETAIL> itTeleFax = correspondenceDetailList.iterator();
		while (itTeleFax.hasNext()) {
			CORRESPONDENCEDETAIL corresDetail = itTeleFax.next();
			if (corresDetail.getType().equalsIgnoreCase("TeleFax"))
				sbTeleFaxNo.append(corresDetail.getValue()).append(" / ");
		}

		if (sbTeleFaxNo.length() > 3)
			return sbTeleFaxNo.substring(0, sbTeleFaxNo.length() - 3);
		return "";
	}

	private String getEmail(List<CORRESPONDENCEDETAIL> correspondenceDetailList) {
		StringBuffer sbEmail = new StringBuffer();
		Iterator<CORRESPONDENCEDETAIL> itEmail = correspondenceDetailList.iterator();
		while (itEmail.hasNext()) {
			CORRESPONDENCEDETAIL corresDetail = itEmail.next();
			if (corresDetail.getType().equalsIgnoreCase("Email"))
				sbEmail.append(corresDetail.getValue()).append(",");
		}

		if (sbEmail.length() > 1)
			return sbEmail.substring(0, sbEmail.length() - 1);
		return "";
	}

	public List saveAlbum(ALBUMMASTER albumMaster, List mediaRelationList, String htmlContent) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		List alertList = new ArrayList();
		String whereClause = "";
		if (albumMaster.getAlbumId() != null)
			whereClause = whereClause + "ALBUMMASTER.albumId !=" + albumMaster.getAlbumId() + " AND ";
		else
			albumMaster.setCreatedDate(new java.util.Date());

		List dataList = hibernateServiceImpl.findObjectsOnObjectBasis("ALBUMMASTER", new String[] { "albumId" }, whereClause + " ALBUMMASTER.albumCode = '" + albumMaster.getAlbumCode() + "'", null);
		if (dataList != null && dataList.size() > 0)
			alertList.add("Album Code " + albumMaster.getAlbumCode() + "is exist");

		dataList = hibernateServiceImpl.findObjectsOnObjectBasis("ALBUMMASTER", new String[] { "albumId" }, "party.partyId = " + albumMaster.getParty().getPartyId() + " AND ALBUMMASTER.albumTitle = '" + albumMaster.getAlbumTitle() + "'", null);
		if (dataList != null && dataList.size() > 0)
			alertList.add("Album Title " + albumMaster.getAlbumTitle() + "is exist for this member");

		Set albumMediaRelationSet = new HashSet();
		int mediaRelSize = mediaRelationList == null ? 0 : mediaRelationList.size();
		for (int index = 0; index < mediaRelSize; index++) {
			ArrayList dataValueList = (ArrayList) mediaRelationList.get(index);
			String filePath = (String) dataValueList.get(1);
			String fileExtn = (String) dataValueList.get(2);
			Boolean isDefault = (Boolean) dataValueList.get(3);
			MEDIARELATION mediaRelation = new MEDIARELATION();
			mediaRelation.setMediaSource(filePath);
			mediaRelation.setMediaType(fileExtn);
			mediaRelation.setIsDefault(isDefault);
			if (dataValueList.size() > 4)
				mediaRelation.setId((Long) dataValueList.get(4));
			else {
				if (htmlContent != null)
					mediaRelation.setMediaDesc("/UploadFile/" + albumMaster.getParty().getPartyId() + "/" + albumMaster.getAlbumTitle() + ".html");
			}
			mediaRelation.setAlbum(albumMaster);

			albumMediaRelationSet.add(mediaRelation);

		}

		albumMaster.setAlbumMediaRelation(albumMediaRelationSet);

		if (htmlContent != null) {
			String path = getServletContext().getRealPath("/UploadFile/" + albumMaster.getParty().getPartyId() + "/" + albumMaster.getAlbumTitle() + ".html");
			File file = new File(path);
			BufferedWriter bw;
			try {
				bw = new BufferedWriter(new FileWriter(file));
				bw.write(htmlContent);
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		hibernateServiceImpl.saveObject(albumMaster);
		alertList.add("Success");
		return alertList;
	}
}
